export MAVEN_HOME=/usr/local/apache/maven
export PATH=$PATH:$MAVEN_HOME/bin

# 项目名称
projectName=mt-tourism-gateway
# 版本号
version=0.0.1-SNAPSHOT
# 容器默认端口，即项目的默认端口
containerDefaultPort=8081
# 宿主机端口，即对外访问的端口
containerPort=8082

# 代码目录根目录
codeRootDir=/data/code/mt-tourism/mt-tourism-common
# 应用临时目录根目录
appRootDir=/app

# 应用临时目录
appDir=${appRootDir}/${projectName}-${version}
# Dockerfile路径
dockerfilePath=${appDir}/Dockerfile
# 镜像名称
imageName=${projectName}:${version}
# Docker容器名称
containerName=${projectName}

mkdir -p ${appDir}

# 拉取远程Git仓库代码并打包
cd ${codeRootDir}/${projectName}
git reset --hard origin/`git branch | grep \* | cut -d ' ' -f2` && git pull
# 构建依赖包
cd /data/code/mt-tourism/mt-tourism-models
mvn install
cd /data/code/mt-tourism/mt-tourism-api
mvn install
cd /data/code/mt-tourism/mt-tourism-utils
mvn install
cd ${codeRootDir}/${projectName}
mvn clean package -Dmaven.test.skip=true

# 复制jar包
rm -rf ${appDir}/*
cp ${codeRootDir}/${projectName}/target/${projectName}-${version}.jar /${appDir}/

# 创建Dockerfile文件
echo 'FROM oracle-jre:8u241-alpine' > ${dockerfilePath}
echo 'VOLUME /tmp' >> ${dockerfilePath}
echo 'ENV EUREKA_PATH http://admin:admin123456@192.168.1.130:8765/eureka' >> ${dockerfilePath}
echo 'ENV FY_EUREKA_PATH http://admin:admin123456@192.168.1.130:9878/eureka' >> ${dockerfilePath}
echo 'ENV MT_HOME dev' >> ${dockerfilePath}
echo 'ADD '${projectName}'-'${version}'.jar app.jar' >> ${dockerfilePath}
echo 'ENTRYPOINT ["java", "-jar", "/app.jar"]' >> ${dockerfilePath}

# 删除已有容器、镜像
if docker ps -f name=$containerName | grep $containerName; 
then 
    docker stop $containerName
    docker rm $containerName
    docker rmi $imageName
fi

# 构建镜像
cd ${appDir}
docker build -t ${imageName} -f ${dockerfilePath} . 

# 启动容器
docker run -idt --name ${containerName} -p ${containerPort}:${containerDefaultPort} ${imageName}
